<?php
namespace Hansn\LaravelAddons\Services;

use Illuminate\Support\Str;

class AddonService
{
    protected $app;
    protected $addon;
    protected $stubPath;
    protected $stubStrMap;

    public function __construct($app)
    {
        $this->app = $app;
        $this->stubPath = config('addons.stubs.path', base_path('vendor/hansn/laravel-addons/stubs'));
        $this->addon = [
            'path' => config('addons.path', 'addons'),
            'namespace' => config('addons.namespace', 'Addons'),
        ];
        $this->stubStrMap = [
            '{Module}' => null,
            '{module}' => null,
            '{Model}' => null,
            '{model}' => null,
            '{namespace}' => $this->addon['namespace'],
        ];

    }

    public function getPath($module)
    {
        return base_path(config('addons.path', 'addons') . ($module ? DIRECTORY_SEPARATOR . $module : ''));
    }

    /**
     * 根据命令行生成文件
     *
     * @param [type] $params
     * @return void
     */
    /**
     * Undocumented function
     *
     * @param [type] $cmd: 命令`php artisan addon:make-cmd`的cmd 部分
     * @param [type] $module: 插件模块名
     * @param [type] $name: 名称
     * @return void
     */
    public function convertStubByCmd($cmd, $module, $name)
    {
        $segments = explode("\\", $name);
        $lastName = $segments[count($segments) - 1];
        $subDir = substr($name, 0, strlen($name) - strlen($lastName));
        $name = $lastName;

        $dir = $subDir ? $subDir : '';
        $this->stubStrMap['{Module}'] = Str::ucfirst($module);
        $this->stubStrMap['{module}'] = Str::lower($module);
        switch ($cmd) {
            case 'controller':
                $this->stubStrMap['{Controller}'] = $subDir . Str::ucfirst($name);
                $this->stubStrMap['{SubDir}'] = "\\".substr($subDir,0,-1);
                $this->stubStrMap['{SubDir}'] = strlen($this->stubStrMap['{SubDir}']) == 1 ? '' : $this->stubStrMap['{SubDir}'];
                $this->createControllerByStub($module, $name, $dir);
                break;
        }

    }

    protected function createControllerByStub($module, $name, $dir)
    {
        $sourceFile = $this->stubPath . DIRECTORY_SEPARATOR . config('addons.generate.controller', 'Http/Controllers/ModuleController.php');
        if (!is_dir(addon_path($module) . "/Http/Controllers/${dir}")) {
            mkdir(addon_path($module) . "/Http/Controllers/${dir}");
        }
        $targetFile = addon_path($module) . "/Http/Controllers/${dir}${name}.php";

        $this->replaceFileByMap($sourceFile,$targetFile,$name);
    }

    protected function replaceFileByMap($sourceFile,$targetFile) {
        file_put_contents($targetFile, file_get_contents($sourceFile));        
        foreach ($this->stubStrMap as $key => $value) {
            if (file_exists($sourceFile)) {
                file_put_contents($targetFile, str_replace($key, $value, file_get_contents($targetFile)));
            }
        }
    }
}
